package org.extreme.schooltalk.parsing;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.extreme.schooltalk.CommonUtils;
import org.extreme.schooltalk.SchoolDTO;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class SchoolFindParser extends DefaultHandler {
	
	private static final String _ITEM = "item";
	private static final String _NO = "no";	
	private static final String _IDX = "idx";
	private static final String _SH_AREA = "sh_area";
	private static final String _SH_NAME = "sh_name";
	private Boolean inItem = false;
	SchoolDTO dto;
	String currentValue = null;
	private List<SchoolDTO> school_list;
	SaxHandler saxHandler;
	
	public SchoolFindParser(InputStream is){
		try {
			school_list = new ArrayList<SchoolDTO>();
			saxHandler = new SaxHandler(this,is);			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public SchoolFindParser(InputStream is,List<SchoolDTO> list){
		try{
			school_list = list;
			saxHandler = new SaxHandler(this,is);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public List<SchoolDTO> getSchoolList(){
		return school_list;
	}
	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.startDocument();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		super.startElement(uri, localName, qName, attributes);
		inItem = true;
		if(localName.equalsIgnoreCase(_ITEM)){
			dto = new SchoolDTO();
		}
	}
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		super.characters(ch, start, length);
		if(inItem){			
			currentValue = new String(ch,start,length);
			Log.i(CommonUtils._LOG_TAG,new String(ch,start,length));
		}
	}
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		super.endElement(uri, localName, qName);
		if(localName.equalsIgnoreCase(_ITEM)){
			school_list.add(dto);
		}else if(localName.equalsIgnoreCase(_NO)){
			dto.setNo(currentValue);
		}else if(localName.equalsIgnoreCase(_IDX)){
			dto.setIdx(currentValue);
		}else if(localName.equalsIgnoreCase(_SH_NAME)){
			dto.setSh_name(currentValue);
		}else if(localName.equalsIgnoreCase(_SH_AREA)){
			dto.setSh_area(currentValue);
		}
		inItem = false;
	}
	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}
	

}
